<?php
defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * 新闻
 * Class News
 * @author heyu
 */
class News extends MY_Controller {
    public $mNews;
    public $mNewsType;

	public function __construct(){
		parent::__construct();
		$this->loadModel('AdmNewsModel', 'mNews');
        $this->loadModel('AdmNewsTypeModel', 'mNewsType');
	}
	
	/**
	 * 首页
	 */
	public function index(){
        $category = $this->mNewsType->adminPcGetList();
        $data = array(
            'category' => $category,
            'title' => '新闻'
        );
		$this->view('shop/news/home', $data, 'datatable,validation,datepicker,select2');
	}

    /**
     * 获取数据
     */
    public function getList(){
        $data = $this->mNews->adminPcGetList();
        foreach ($data['data'] as $k => $v){
            $data['aaData'][$k][] = $v['title'];
            $data['aaData'][$k][] = $v['type_name'];
            $data['aaData'][$k][] = $v['keywords'];
            $data['aaData'][$k][] = $v['source'];
            $data['aaData'][$k][] = isset($v['read_number']) ? $v['read_number'] : 0;
            $topName = $v['top']==1 ? '置顶' : '取消置顶';
            $statusName = $v['status']==1 ? '发布' : '取消发布';
            $top = isset($v['top']) ? $this->getTop($v['top'], true) : $this->getTop(1, true);

            $data['aaData'][$k][] ="<a href='".getUrl('shop/news/changeStatus?id='.$v['id'].'&type=2').
                "' class='ajax-request-btn deco' alert-message='是否确认".$topName."'>".
                $top."</a>";
            $data['aaData'][$k][] = "<a href='".getUrl('shop/news/changeStatus?id='.$v['id']).'&type=1'.
                "' class='ajax-request-btn deco' alert-message='是否确认".$statusName."'>".
                $this->getStatus($v['status'], true)."</a>";

            $data['aaData'][$k][] = "<input type='text' value='".$v['sort']."' class='sort' data-id='".$v['id']."'>";
            $data['aaData'][$k][] = dateFormat($v['addtime']);


            $btnConfig = adminCreateBtn(array(
                    'label' => ' 编辑',
                    'attr' => array(
                        'href' => getUrl('shop/news/edit').'?id='.$v['id'],
                        'class' => 'btn btn-xs blue-stripe default edit-btn',
                        'id' => $v['id'],
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'group',
                        'key' => 'edit'
                    )
                ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => '预览',
                    'attr' => array(
                        'href' => 'javascript:;',
                        'class' => 'preview btn btn-xs green-stripe default',
                        'id' => $v['id']
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'group',
                        'key' => 'status'
                    )
                ));
            $btnConfig .= ' '.adminCreateBtn(array(
                    'label' => '删除',
                    'attr' => array(
                        'href' => getUrl('shop/news/delete?id='.$v['id']),
                        'alert-message' => "确认是否删除“ ".$v['title']." ”？",
                        'class' => 'ajax-request-btn btn btn-xs red-stripe default',
                    ),
                    'tag' => 'a',
                    'permissions' => array(
                        'module' => 'group',
                        'key' => 'status'
                    )
                ));
            $data['aaData'][$k][] = $btnConfig;
        }
        unset($data['data']);
        echo json_encode($data);
    }

    /**
     * 详情
     */
    public function getInfo(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);
        $id = (int)post('id');
        $info = $this->mNews->getInfo($id);
        if (!$info){
            $this->ajaxReturn(0, '新闻不存在');
        }
        $this->ajaxReturn(1, '', $info);
    }

    /**
     * 添加
     */
    public function add(){
        $category = $this->mNewsType->adminPcGetList();
        $data = array(
            'category' => $category,
            'add' => true,
            'number' => 1,
            'title' => '添加新闻'
        );
        $this->view('shop/news/from', $data, 'validation,datepicker,select2,webuploader,ueditor');
    }

    /**
     * 编辑
     */
    public function edit(){
        $id = (int)get('id');
        if (!$id){
            show_404();
        }
        $category = $this->mNewsType->adminPcGetList();
        $info = $this->mNews->getInfo($id);

        $data = array(
            'info' => $info,
            'number' => $info['type'] == 1 ?1:3 ,
            'category' => $category,
            'add' => false,
            'title' => '编辑新闻'
        );
        $this->view('shop/news/from', $data, 'validation,datepicker,select2,webuploader,ueditor');
    }

    /**
     * 保存
     */
    public function save(){
        //表单验证
        $vConf = array(
            array('title', '新闻名称', 'required'),
            array('keywords', '关键字', 'required'),
            array('source', '来源', 'required'),
            array('sort', '排序', 'required|is_natural_no_zero'),
            array('top', '是否置顶', 'required|in_list[1,2]'),
            array('status', '状态', 'required|in_list[1,2]'),
            array('type', '类别', 'required|in_list[1,2]'),
            array('content', '内容', 'required'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');
        $type = (int)post('type');
        $typeIds = post('typeIds'); // 分类
        $images = post('imgs');

        $category = $this->mNewsType->getInfoByIds($typeIds);
        if (count($typeIds) != count($category)){
            $this->ajaxReturn(0, '分类信息错误');
        }
        if($type == 2 && count($images) != 3){
            $this->ajaxReturn(0, '三图请上传三张');
        }
        if($type == 1 && count($images) != 1){
            $this->ajaxReturn(0, '单图请上传一张');
        }
        $data = array(
            'title' => post('title'),
            'type_ids' => ','.implode(',', $typeIds).',',
            'content' => post('content'),
            'type' => $type,
            'keywords' => trim(post('keywords')),
            'top' => post('top'),
            'status' => post('status'),
            'sort' => post('sort'),
            'source' => trim(post('source'))
        );
        $this->db->trans_begin();
        if( ! $id){
            $data['addtime'] = time();
            if( ! ($id = $this->mNews->save($data))){
                $this->db->trans_rollback();
                $this->ajaxReturn(0, '保存失败');
            }
        }else{
            $info = $this->mNews->getInfo($id);
            if (!$info){
                $this->ajaxReturn(0, '新闻不存在');
            }
        }

        $path = 'uploads/news/'.$id.'/title/';

        //foreach ($images as $k => $v){
            foreach ($images as $kk => $vv){
                $tA = explode('?', str_replace(base_url(), '', $vv));
                $img = $tA[0];

                if (!file_exists($img)) {
                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '标题图片错误1');
                }
                $size = getimagesize($img);
                $img = imageThumb($img, $path, $size[0], $size[1]);
                if (!$img) {

                    $this->db->trans_rollback();
                    $this->ajaxReturn(0, '标题图片错误2');
                }
                $data['imgs'][] = $img;
            }
        //}
        $data['imgs'] = json_encode($data['imgs'], JSON_UNESCAPED_UNICODE);
        if( ! $this->mNews->save($data, $id)){
            $this->db->trans_rollback();
            $this->ajaxReturn(0, '保存失败');
        }
        $this->db->trans_commit();
        $this->ajaxReturn(1, '保存成功', null, getUrl('shop/news'));
    }

    /**
     * 删除
     */
    public function delete(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf, array('id' => get('id')));
        $id = (int)get('id');
        $info = $this->mNews->getInfo($id, true);
        if (!$info){
            $this->ajaxReturn(0, '新闻不存在或已删除');
        }
        $tA = $this->mNews->deleteNews($id);
        if (!$tA){
            $this->ajaxReturn(0, '删除失败');
        }
        $this->ajaxReturn(1, '删除成功');
    }

    /**
     * 修改排序
     */
    public function changeSort(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('sort', 'sort', 'required|is_natural_no_zero'),
        );
        $this->formDataValidation($vConf);

        $id = (int)post('id');
        $sort = (int)post('sort');
        $info = $this->mNews->getInfo($id, true);

        if (!$info){
            $this->ajaxReturn(0, '新闻不存在'.$id);
        }
        $tA = $this->mNews->save(array('sort' => $sort), $id);
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 改变状态
     */
    public function changeStatus(){
        //表单验证
        $vConf = array(
            array('id', 'id', 'required|is_natural_no_zero'),
            array('type', 'type', 'required|in_list[1,2]'),
        );
        $this->formDataValidation($vConf, array('id' => get('id'), 'type' => get('type')));

        $id = (int)get('id');
        $type = (int)get('type');
        $info = $this->mNews->getInfo($id, true);

        if (!$info){
            $this->ajaxReturn(0, '新闻不存在');
        }
        if ($type == 1){
            $status = $info['status']==1 ? 2 : 1;
            $tA = $this->mNews->save(array('status' => $status), $id);
        }else{
            $top = $info['top']==1 ? 2 : 1;
            $tA = $this->mNews->save(array('top' => $top), $id);
        }
        if (!$tA){
            $this->ajaxReturn(0, '保存失败');
        }
        $this->ajaxReturn(1, '保存成功');
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @param 	bool $show
     * @return	string
     */
    protected function getStatus($status = null, $show = false){
        $config = array(1 => '未发布', 2 => '已发布');

        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }

        return'';
    }

    /**
     * 获取状态显示样式
     * @param 	integer $status
     * @param 	bool $show
     * @return	string
     */
    protected function getTop($status = null, $show = false){
        $config = array(1 => '普通', 2 => '置顶');

        if( ! $status){
            return $config;
        }

        if($status && ! isset($config[$status])){
            return '';
        }

        if( ! $show){
            return $config[$status];
        }


        if($status == 1){
            return '<span class="label label-success">'.$config[$status].'</span>';
        }else if($status == 2){
            return '<span class="label label-danger">'.$config[$status].'</span>';
        }

        return'';
    }
}
